package com.gzhryc.shared_device.oem.h5.mng.controllers.place;

import com.gzhryc.common.DateTools;
import com.gzhryc.common.MatrixToImageWriter;
import com.gzhryc.common.StringTools;
import com.gzhryc.common.config.PropertyTools;
import com.gzhryc.common.data.dto.AjaxResult;
import com.gzhryc.common.data.dto.ListResult;
import com.gzhryc.common.data.dto.SelectResult;
import com.gzhryc.common.exceptions.LogicException;
import com.gzhryc.common.logging.Logger;
import com.gzhryc.servlet.DtoConstants;
import com.gzhryc.servlet.WebUtils;
import com.gzhryc.servlet.annotation.Route;
import com.gzhryc.shared_device.base.enums.EOperatorType;
import com.gzhryc.shared_device.base.models.OperateInfo;
import com.gzhryc.shared_device.bxscn.code.dao.models.PortableEnergyBatteryPlaceCount;
import com.gzhryc.shared_device.bxscn.code.services.PortableEnergyBatteryService;
import com.gzhryc.shared_device.common.CountryAreaUtils;
import com.gzhryc.shared_device.common.device.dao.models.PlaceDeviceCount;
import com.gzhryc.shared_device.common.device.services.DeviceService;
import com.gzhryc.shared_device.oem.code.place.dao.db.PlacePhysicalStoreAddress;
import com.gzhryc.shared_device.oem.code.place.dao.enums.PlacePhysicalStoreEnum;
import com.gzhryc.shared_device.oem.code.place.services.PlacePhysicalStoreAddressService;
import com.gzhryc.shared_device.oem.code.place.services.PlacePhysicalStoreTypeService;
import com.gzhryc.shared_device.oem.code.user.dao.db.User;
import com.gzhryc.shared_device.oem.code.user.services.UserService;
import com.gzhryc.shared_device.oem.h5.mng.WebConstants;
import com.gzhryc.shared_device.oem.code.place.dao.db.PlacePhysicalStore;
import com.gzhryc.shared_device.oem.code.place.services.PlacePhysicalStoreService;
import com.gzhryc.shared_device.oem.code.place.services.dto.PlacePhysicalStoreSearch;
import com.gzhryc.shared_device.oem.h5.mng.dto.place.PlaceListItem;
import com.gzhryc.system.SysConstants;
import com.gzhryc.system.dao.db.Manager;

import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 实体店相关页面控制器
 * @version 2022-11-08
 */
public class PlacePhysicalStoreController {

    static Logger log = Logger.getLogger(PlacePhysicalStoreController.class);

    @Route(value = { "/place/physical_store/list.html" })
    public String list(HttpServletRequest request) {
        request.setAttribute("stateList", PlacePhysicalStoreEnum.State.values());
        return "/place/physical_store/list.html";
    }

    @Route(value = "/place/physical_store/list.data")
    public ListResult<PlaceListItem> listData(HttpServletRequest request) {
        ListResult<PlaceListItem> result = new ListResult<>(DtoConstants.NULL_DATA, "暂无数据");
        PlacePhysicalStoreSearch search = WebUtils.getParameter(request, PlacePhysicalStoreSearch.class);
        Integer pageNo = WebUtils.getInteger(request, "page", 1);
        Integer pageLimit = WebUtils.getInteger(request, "limit", WebConstants.PAGE_LIMIT);

        result.getBody().setTotal(PlacePhysicalStoreService.self().countJoinBySearch(search));
        List<PlacePhysicalStore> placePhysicalStoreList = PlacePhysicalStoreService.self().findJoinBySearch(search, pageNo, pageLimit);
        if(placePhysicalStoreList != null && placePhysicalStoreList.size() > 0) {
            result.setCode(DtoConstants.SUCCESS,null);
            result.getBody().setData(new ArrayList<>());
            List<Long> placeIds = new ArrayList<>();
            String resDomain = WebConstants.getResDomain(request);
            for(PlacePhysicalStore physicalStore : placePhysicalStoreList){
                placeIds.add(physicalStore.getId());

                PlaceListItem item = new PlaceListItem();
                item.setId(physicalStore.getId());
                if(StringTools.isNotBlank(physicalStore.getThumbnailImg())) {
                    item.setThumbnailImg(resDomain + physicalStore.getThumbnailImg());
                }
                item.setName(physicalStore.getName());
                item.setTypeNames(physicalStore.getTypeNames());
                item.setAreaName(physicalStore.getAreaName());
                if(physicalStore.getUser() != null){
                    item.setUserName(physicalStore.getUser().getName() + "("+physicalStore.getUserId()+")");
                }else{
                    item.setUserName(physicalStore.getUserId().toString());
                }
                item.setState(physicalStore.getState());
                item.setStateName(physicalStore.getStateName());
                item.setDeviceCount(0);
                item.setCreateDate(physicalStore.getCreateDate());
                result.getBody().getData().add(item);
            }

            List<PortableEnergyBatteryPlaceCount> placeBatteryCountList = PortableEnergyBatteryService.self().findPlaceCountByPlaceIds(placeIds);
            List<PlaceDeviceCount> placeDeviceCountList = DeviceService.self().countPlaceByPlaceIds(placeIds);
            for(PlaceListItem item : result.getBody().getData()) {
                if (placeDeviceCountList != null && placeDeviceCountList.size() > 0) {
                    for(PlaceDeviceCount placeDeviceCount : placeDeviceCountList){
                        if(placeDeviceCount.getPlaceId().equals(item.getId())){
                            item.setDeviceCount(placeDeviceCount.getDeviceCount().intValue());
                            break;
                        }
                    }
                }
                
                if (placeBatteryCountList != null && placeBatteryCountList.size() > 0) {
                    for(PortableEnergyBatteryPlaceCount placeBatteryCount : placeBatteryCountList){
                        if(placeBatteryCount.getPlaceId().equals(item.getId())){
                            item.setDeviceCount(item.getDeviceCount() + placeBatteryCount.getDeviceCount().intValue());
                            break;
                        }
                    }
                }
            }
        }
        return result;
    }

    @Route(value = { "/place/physical_store/add.html" })
    public String add(HttpServletRequest request) {
    	if(WebConstants.isLocalRes()) {
    	     return "/place/physical_store/edit2.html";
    	}
        return "/place/physical_store/edit.html";
    }

    @Route(value = { "/place/physical_store/add.do" })
    public AjaxResult doAdd(HttpServletRequest request,HttpSession session) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR, "新增失败，请稍后再试");
        PlacePhysicalStore place = WebUtils.getParameter(request, PlacePhysicalStore.class);
        if (place.getUserId() == null) {
            User user = WebUtils.getParameter(request,"user",User.class);
            if(user != null){
                User temp = UserService.self().getByPhone(user.getPhone());
                if(temp != null){
                    place.setUserId(temp.getId());
                }else{
                    result.setMsg("手机号未注册代理");
                }
            }
            result.setMsg("请选择网点所属代理");
            return result;
        }
        if (StringTools.isBlank(place.getAreaCode())) {
            result.setMsg("请选择网点所在省市地区");
            return result;
        }
        String[] areaCodeStr = place.getAreaCode().split(",");
        String[] areaNames = CountryAreaUtils.getAreaNames(areaCodeStr);
        if (areaNames == null || areaNames.length < 3) {
            result.setMsg("请选择正确的省市地区");
            return result;
        }

        if (StringTools.isNotBlank(areaNames[0])) {
            place.setProvince(areaNames[0]);
        }
        if (StringTools.isNotBlank(areaNames[1])) {
            place.setCity(areaNames[1]);
        }
        if (StringTools.isNotBlank(areaNames[2])) {
            place.setCityArea(areaNames[2]);
        }

        String[] typeCodes = place.getTypeCodes().split(",");
        String[] typeName = PlacePhysicalStoreTypeService.self().getNames(typeCodes);
        if (typeName != null && typeName.length > 0) {
            place.setTypeNames(StringUtils.join(typeName, ","));
        }

        //营业时间
        String businessTimeStr = WebUtils.getString(request,"businessTimeStr");
        if(StringTools.isNotBlank(businessTimeStr)){
            String[] timeArray = businessTimeStr.split(" - ");
            if(timeArray != null && timeArray.length == 2){
                place.setOpenTime(DateTools.changeHHmm(timeArray[0]));
                place.setCloseTime(DateTools.changeHHmm(timeArray[1]));
            }
        }
        Manager manager = WebUtils.getAttribute(session, SysConstants.SESSION_LOGIN_MANAGER, Manager.class);
        
        OperateInfo operateInfo = new OperateInfo(WebConstants.PROGRAM_TYPE,WebConstants.PROGRAM_TYPE_NAME);
        operateInfo.setOperator(EOperatorType.Manager.index(),manager.getFullName());

        try {
            if (PlacePhysicalStoreService.self().add(place,operateInfo)) {
                result.setCode(DtoConstants.SUCCESS, null);
            }
        } catch (LogicException e) {
            result.setMsg(e.getMessage());
        }
        return result;
    }

    @Route(value = { "/place/physical_store/info.html" })
    public String info(HttpServletRequest request) {
        Long id = WebUtils.getLong(request,"id");
        PlacePhysicalStore placePhysicalStore = PlacePhysicalStoreService.self().getById(id);
        if(placePhysicalStore != null) {
            WebUtils.setAttribute(request, placePhysicalStore);
            PlacePhysicalStoreAddress mailAddress = PlacePhysicalStoreAddressService.self().getById(id);
            if(mailAddress != null) {
                request.setAttribute("mailAddress",mailAddress);
            }
        }
        return "/place/physical_store/info.html";
    }

    @Route(value = { "/place/physical_store/update.html" })
    public String update(HttpServletRequest request) {
        Long id = WebUtils.getLong(request,"id");
        PlacePhysicalStore placePhysicalStore = PlacePhysicalStoreService.self().getById(id);
        if(placePhysicalStore != null) {
            WebUtils.setAttribute(request, placePhysicalStore);
            User user = UserService.self().getById(placePhysicalStore.getUserId());
            request.setAttribute("userInfo",user.getName() + "("+user.getPhone()+")");
        }
    	if(WebConstants.isLocalRes()) {
    	     return "/place/physical_store/edit2.html";
    	}
        return "/place/physical_store/edit.html";
    }

    @Route(value = { "/place/physical_store/update.do" })
    public AjaxResult doUpdate(HttpServletRequest request) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR, "修改失败，请稍后再试");
        PlacePhysicalStore place = WebUtils.getParameter(request, PlacePhysicalStore.class);
        try {
            if(StringTools.isBlank(place.getTypeCodes())){
                result.setMsg("请选择网点类型");
                return result;
            }
            if(StringTools.isBlank(place.getAreaCode())){
                result.setMsg("请选择网点所在省市地区");
                return result;
            }
            String[] areaCodeStr = place.getAreaCode().split(",");
            String[] areaNames = CountryAreaUtils.getAreaNames(areaCodeStr);
            if (areaNames == null || areaNames.length < 3) {
                result.setMsg("请选择正确的省市地区");
                return result;
            }

            if (StringTools.isNotBlank(areaNames[0])) {
                place.setProvince(areaNames[0]);
            }
            if (StringTools.isNotBlank(areaNames[1])) {
                place.setCity(areaNames[1]);
            }
            if (StringTools.isNotBlank(areaNames[2])) {
                place.setCityArea(areaNames[2]);
            }

            String[] typeCodes = place.getTypeCodes().split(",");
            String[] typeName = PlacePhysicalStoreTypeService.self().getNames(typeCodes);
            if (typeName != null && typeName.length > 0) {
                place.setTypeNames(StringUtils.join(typeName,","));
            }else{
                result.setMsg("请选择正确的网点类型");
                return result;
            }

            //营业时间
            String businessTimeStr = WebUtils.getString(request,"businessTimeStr");
            if(StringTools.isNotBlank(businessTimeStr)){
                String[] timeArray = businessTimeStr.split(" - ");
                if(timeArray != null && timeArray.length == 2){
                    place.setOpenTime(DateTools.changeHHmm(timeArray[0]));
                    place.setCloseTime(DateTools.changeHHmm(timeArray[1]));
                }
            }

            if (PlacePhysicalStoreService.self().updateNotNull(place)) {
                result.setCode(DtoConstants.SUCCESS, null);
            }
        } catch (LogicException e) {
            result.setMsg(e.getMessage());
        }
        return result;
    }

    @Route(value = { "/place/physical_store/mail.html" })
    public String mail(HttpServletRequest request) {
        Long id = WebUtils.getLong(request,"id");
        PlacePhysicalStore placePhysicalStore = PlacePhysicalStoreService.self().getById(id);
        if(placePhysicalStore != null) {
            request.setAttribute("place",placePhysicalStore);
            PlacePhysicalStoreAddress mailAddress = PlacePhysicalStoreAddressService.self().getById(id);
            if(mailAddress != null) {
                WebUtils.setAttribute(request, mailAddress);
            }else{
                request.setAttribute("areaCode",placePhysicalStore.getAreaCode());
            }
        }
        return "/place/physical_store/mail.html";
    }

    @Route(value = { "/place/physical_store/mail/save.do" })
    public AjaxResult doSaveMail(HttpServletRequest request) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR, "保存失败，请稍后再试");
        PlacePhysicalStoreAddress address = WebUtils.getParameter(request, PlacePhysicalStoreAddress.class);
        if(StringTools.isBlank(address.getAreaCode())){
            result.setMsg("请选择地址所在省市地区");
            return result;
        }
        String[] areaCodeStr = address.getAreaCode().split(",");
        String[] areaNames = CountryAreaUtils.getAreaNames(areaCodeStr);
        if (areaNames == null || areaNames.length < 3) {
            result.setMsg("请选择正确的省市地区");
            return result;
        }

        if (StringTools.isNotBlank(areaNames[0])) {
            address.setProvince(areaNames[0]);
        }
        if (StringTools.isNotBlank(areaNames[1])) {
            address.setCity(areaNames[1]);
        }
        if (StringTools.isNotBlank(areaNames[2])) {
            address.setCityArea(areaNames[2]);
        }
        if(PlacePhysicalStoreAddressService.self().save(address)){
            result.setCode(DtoConstants.SUCCESS, null);
        }
        return result;
    }

    @Route(value = { "/place/physical_store/qrcode.html" })
    public String qrcode(HttpServletRequest request) {
        Long placeId = WebUtils.getLong(request, "placeId");
        if (placeId != null) {
            PlacePhysicalStore physicalStore = PlacePhysicalStoreService.self().getById(placeId);
            if (physicalStore != null) {
                String httpDomain = PropertyTools.get().getString("httpDomain");
                String url = httpDomain + "/place/physical_store/" + physicalStore.getId();
                request.setAttribute("url", url);
            }
        }
        return "/place/physical_store/qrcode.html";
    }

    @Route(value = { "/place/physical_store/qrcode.jpg" })
    public void qrcodeImg(HttpServletRequest request, HttpServletResponse response) {
        Long placeId = WebUtils.getLong(request, "placeId");
        if (placeId != null) {
            PlacePhysicalStore physicalStore = PlacePhysicalStoreService.self().getById(placeId);
            if (physicalStore != null) {
                try {
                    String httpDomain = PropertyTools.get().getString("httpDomain");
                    String url = httpDomain + "/place/physical_store/" + physicalStore.getId();
                    WebUtils.exportJPEG(response);
                    MatrixToImageWriter.writeToStream(url, 400, 300, "jpeg", response.getOutputStream());
                } catch (IOException e) {
                    log.error(e.getMessage(), e);
                }
            }
        }
    }

    @Route(value = { "/place/physical_store/del.do" })
    public AjaxResult doDel(HttpServletRequest request) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR, "删除失败，请稍后再试");
        Long id = WebUtils.getLong(request, "id");
        try {
            if (PlacePhysicalStoreService.self().deleteById(id)) {
                //移除便携式电池部署
                PortableEnergyBatteryService.self().undeployByPlaceId(id);
                result.setCode(DtoConstants.SUCCESS, null);
            }
        } catch (LogicException e) {
            result.setMsg(e.getMessage());
        }
        return result;
    }

    @Route(value = "/place/gps/map.html")
    public String map(HttpServletRequest request) {
        return "/place/gps/map.html";
    }

    @Route("/place/physical_store/select.data")
    public SelectResult selectData(HttpServletRequest request) {
        SelectResult result = new SelectResult(DtoConstants.SUCCESS);
        String term = request.getParameter("term");
        Integer page = WebUtils.getInteger(request, "page", 1);

        PlacePhysicalStoreSearch search = new PlacePhysicalStoreSearch();
        search.setName(term);
        Long total = PlacePhysicalStoreService.self().countJoinBySearch(search);
        List<PlacePhysicalStore> list = PlacePhysicalStoreService.self().findJoinBySearch(search, page, WebConstants.PAGE_LIMIT);
        if (list != null) {
            for (PlacePhysicalStore place : list) {
                SelectResult.Item item = new SelectResult.Item();
                item.setId(place.getId().toString());
                item.setText(place.getName());
                result.getBody().getData().add(item);
            }
        }
        result.getBody().setPage(page);
        result.getBody().setLimit(WebConstants.PAGE_LIMIT);
        result.getBody().setTotal(total);
        return result;
    }
}
